
module sn76849_latch_ctrl(
  input  wire       clock_i,  //PSG Clock -- 3.6MHz 
  input  wire       clk_en_i, //Global Enable -- high active
  input  wire       res_n_i,  //PSG Reset -- low active
  input  wire       we_n_i,   //CPU Write enable -- low active
  input  wire [7:0] d_i,      //CPU Write data -- 8bits
  output wire       ready_o,  //High acive, indicates the data has been read
  output wire       tone1_we_o, //Tone channel 1 write enable 
  output wire       tone2_we_o, //Tone channel 2 write enable 
  output wire       tone3_we_o, //Tone channel 3 write enable 
  output wire       noise_we_o, //Noise channel  write enable
  output wire       r2_0        //Control register or volume select -- 0->control 1->volume
);

reg [2:0] reg_q; //Channel(reg_q[6:5]) and register(reg_q[4]) select 
always @(posedge clock_i or negedge res_n_i)begin
    if(!res_n_i)
	reg_q <= #1 3'b0;
    else if(!clk_en_i)
	reg_q <= #1 reg_q;
    else (!we_n_i && d_i[7])
	reg_q <= #1 d_i[6:4]; 
end

reg we_q;
always @(posedge clock_i or negedge res_n_i)begin
    if(!res_n_i)
	we_q <= #1 1'b0;
    else if(!clk_en_i)
	we_q <= #1 we_q;
    else if(!we_n_i)
	we_q <= #1 1'b1;
    else
	we_q <= #1 1'b0;
end

//Now not do cpu interface sync, so set ready_q is 0.
assign ready_o = 1'b0;

assign tone1_we_o = (reg_q[2:1]==2'b00) & we_q;
assign tone2_we_o = (reg_q[2:1]==2'b01) & we_q;
assign tone3_we_o = (reg_q[2:1]==2'b10) & we_q;
assign noise_we_o = (reg_q[2:1]==2'b11) & we_q;
assign r2_o       = reg_q[0];

endmodule
